import datetime

from django.utils import timezone
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU, GoodsVisitCount
from users.models import User


class UserDayActiveView(APIView):
    # 指定当前视图自己的权限控制方式，不再使用全局权限控制方式
    permission_classes = [IsAdminUser]

    @staticmethod
    def get(request):
        # 日活
        # 2020-12-19 06:52:22.495874
        # 设置今天的0时0分0秒0毫秒 用于后面查找
        curr_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        user_count = User.objects.filter(last_login__gte=curr_time).count()
        response_data = {
            'date': curr_time.date(),
            'count': user_count
        }
        return Response(response_data)


# GET /meiduo_admin/statistical/day_orders/
class UserDayOrdersView(APIView):
    permission_classes = [IsAdminUser]

    @staticmethod
    def get(request):
        # 下单用户
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(orders__create_time__gte=now_date).distinct().count()
        response_data = {
            'date': now_date.date(),
            'count': count
        }
        return Response(response_data)


class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    @staticmethod
    def get(request):
		# 月新增用户
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        begin_date = now_date - timezone.timedelta(days=29)

        current_date = begin_date
        month_li = []
        while current_date <= now_date:
            next_date = current_date + timezone.timedelta(days=1)
            count = User.objects.filter(date_joined__gte=current_date,
                                        date_joined__lt=next_date).count()
            month_li.append({
                'count': count,
                'date': current_date.date()
            })

            current_date = next_date
        return Response(month_li)


class UserDayIncrementView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 日增用户
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        count = User.objects.filter(date_joined__gte=now_date).count()
        return Response({'count': count, 'date': timezone.now().date()})


class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 用户总数
        try:
            count = User.objects.filter(is_staff=False).count()
        except Exception:
            return Response({'message': '数据库操作失败'})
        return Response({'count': count, 'date': timezone.now().date()})


class GoodsDayViewsView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        """当天的商品访问量"""
        now_date = timezone.now().date()
        try:
            skus = GoodsVisitCount.objects.filter(date=now_date).values('category', 'count')
        except Exception:
            return Response({'message': '数据库操作失败'})
        return Response(skus)
